require.config({
    paths: {
        'columntoggle': '../addons/facrm/js/columntoggle',
    }
});
define(['jquery', 'bootstrap', 'backend', 'table', 'form','columntoggle'], function ($, undefined, Backend, Table, Form,Columntoggle) {
//本地缓存定义
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/clues/index/index',
                    add_url: 'facrm/clues/index/add',
                    edit_url: 'facrm/clues/index/edit',
                    del_url: 'facrm/clues/index/del',
                    multi_url: '',
                    table: '',
                }
            });
            var table = $("#clues");
            var toggle_show_key="searchclues";
            var toggle_show=localStorage.getItem(toggle_show_key)==0?false:true;
            var status_obj={1: __('已转客户'), 0: __('未转客户'), '-1': __('无效线索')};
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                if (from_type == "need") {
                    //如果是需要跟进的
                    $(".commonsearch-table").removeClass("hidden");
                    $("input[name='next_time']").val(Moment().year(Moment().year() - 20).startOf('year').format('YYYY-MM-DD H:mm:ss') + ' - ' + Moment().endOf('day').format('YYYY-MM-DD H:mm:ss'));
                }
                var  scene_id;
                $.each(scene_list, function(i) {
                    scene_id=i; //获取键值
                    return false
                });
                $(".commonsearch-table select[name=scene_id]").val(scene_id);


            });
            var columnss = [
                {checkbox: true},
                {
                    field: 'scene_id',
                    title: __('线索场景'),
                    visible: false,
                    formatter: function (v, r) {
                        return scene_list[v];
                    }, searchList: scene_list
                },
            ];

            if (Config.fields && Object.keys(Config.fields).length > 0) {
                var fields = JSON.parse(Config.fields);
                for (var i = 0; i < fields.length; i++) {
                    if (fields[i].hasOwnProperty('formatter'))
                        fields[i].formatter = eval(fields[i].formatter);
                    if (fields[i].hasOwnProperty('events'))
                        fields[i].events = eval(fields[i].events);
                    if (fields[i].hasOwnProperty('searchList'))
                        fields[i].searchList = eval(fields[i].searchList);
                    if (fields[i].hasOwnProperty('cellStyle'))
                        fields[i].cellStyle = eval(fields[i].cellStyle);
                    columnss.push( fields[i]);
                }
            }
            //追加操作字段
            columnss.push({
                field: 'operate',
                title: __('Operate'),
                table: table,
                width: "180px",
                events: Table.api.events.operate,
                formatter: Table.api.formatter.operate,
                buttons: [
                    {
                        name: 'record',
                        text:  __('跟进'),
                        title: function ( row) {
                            return '跟进线索-'+row.name;
                        },
                        icon: 'fa fa-commenting-o',
                        classname: 'btn btn-xs btn-danger btn-addtabs',
                        url: 'facrm/clues/record/add',
                    },
                    {
                        name: 'transform',
                        text:  __('转客'),
                        title:  __('转化成客户'),
                        url: 'facrm/clues/index/transform',
                        icon: 'fa fa-arrow-right',
                        classname: 'btn btn-xs btn-info   btn-dialog',
                        hidden:function (row) {
                            if (row.status==1) return true;
                            return  false
                        }
                    },
                    {
                        name: 'customer',
                        text:  __('客户'),
                        title:  __('客户详情'),
                        url: function(row){
                            return  'facrm/customer/index/detail/ids/'+row.customer_id;
                        },
                        icon: 'fa fa-user fa-fw',
                        classname: 'btn btn-xs btn-success   btn-dialog',
                        hidden:function (row) {
                            if (row.customer_id) return false;
                            return  true;
                        }
                    },

                ]
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    columnss
                ],
                onLoadSuccess: function () {
                    // 载入成功时执行
                    loadSuccess("clues")
                },
                onColumnSwitch: function () {
                    // 切换列时执行columnSwitch方法
                    columnSwitch("clues","clues_table")
                },
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
                searchFormVisible:toggle_show, //打开搜索

            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            // 绑定TAB事件
            $('.panel-heading ul[data-field] li a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field = $(this).closest("ul").data("field");
                var value = $(this).data("value");
                $(".commonsearch-table input[name=" + field + "]").val(value);
                return false;
            });
            // 批量放入公共事件
            $("#toolbar").on('click', '.btn-discard', function () {
                var that = this;
                var ids = Table.api.selectedids(table);
                Layer.confirm(
                    __('确定放入公共 %s 项?', ids.length),
                    {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                    function (index) {
                        Table.api.multi("del1", ids, table, that);
                        Layer.close(index);
                    }
                );
            });

            // 批量删除事件
            $("#toolbar").on('click', '.btn-dels', function () {
                var that = this;
                var ids = Table.api.selectedids(table);
                Layer.confirm(
                    __('确定删除 %s 项?', ids.length),
                    {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                    function (index) {
                        Table.api.multi("del1", ids, table, that);
                        Layer.close(index);
                    }
                );
            });

            // 批量转移
            $("#toolbar").on('click', '.btn-divert', function () {
                var that = this;
                var ids = Table.api.selectedids(table);
                if (ids.length <=0) {
                    return;
                }
                var title = $(that).data('title') || $(that).attr("title") || __('Edit');
                var url = $(that).data('url');
                var data = $(that).data() || {};
                delete data.title;
                Fast.api.open(url + "/ids/" + ids, title, data);
            });

            //批量发邮件
            $(".btn-send-emails").click(function () {
                var that = this;
                var title = $(that).data('title') || $(that).attr("title") || __('批量发邮件');
                var url = $(that).data('url');
                var data = $(that).data() || {};
                delete data.title,data.url;
                var ids = Table.api.selectedids(table);
                if (ids.length <=0) {
                    return;
                }
                data.typesid=ids;
                parent.Fast.api.open(url+"?data="+encodeURI(JSON.stringify(data)), title, data);
            });

            $("button[name='commonSearch']").bind("click",function(){
                localStorage.setItem(toggle_show_key,(toggle_show?0:1));
            });

        },
        add: function () {
            Controller.api.bindevent();
        },
        divert: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/clues/record/index/clues_id/' + clues_id,
                    files_url: 'facrm/clues/record/files/clues_id/' + clues_id,
                }
            });
            var table = $("#tableflow");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbar1',
                columns: [
                    [
                        {field: 'id', title: 'ID'},
                        {field: 'content', title: __('content'), operate: 'LIKE'},
                        {field: 'create_user.nickname', title: __('创建人'), operate: false, search: false},
                        {field: 'create_user_id', title: __('创建人'), visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname"'},
                        {
                            field: 'create_time',
                            title: __('创建时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
							extend: 'autocomplete="off"'
                        },
                        {
                            field: 'next_time',
                            title: __('下次跟进'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
							extend: 'autocomplete="off"'
                        },
                        {
                            field: 'record_type', title: __('跟进类型'), formatter: function (v, r) {
                                return record_type_list[v];
                            }, searchList: record_type_list
                        },

                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);


            //附件
            var files = $("#t-files");
            files.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.files_url,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbar-files',
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: false,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: false,
                //分页大小
                pageSize: 1,
                showColumns: false,
                showToggle: false,
                showExport: false,
                showSearch: false,
                pagination: false,
                columns: [
                    [
                        {field: 'url', title: __('预览'), formatter: Controller.api.formatter.thumb, operate: false},
                        {
                            field: 'create_time',
                            title: __('创建时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
							extend: 'autocomplete="off"'
                        },

                    ]
                ],
            });


        },
        common: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/clues/index/common',
                    multi_url: '',
                    table: '',
                }
            });

            var table = $("#clues_common");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: 'ID'},
                        {field: 'name', title: __('名称'), operate: "LIKE"},
                        {
                            field: 'level', title: __('级别'), formatter: function (v, r) {
                                return levelList[v];
                            }, searchList: levelList
                        },
                        {
                            field: 'industry', title: __('行业'), formatter: function (v, r) {
                                return industryList[v];
                            }, searchList: industryList
                        },
                        {
                            field: 'source', title: __('来源'), formatter: function (v, r) {
                                return sourceList[v];
                            }, searchList: sourceList
                        },
                        {field: 'telephone', title: __('电话'), operate: 'LIKE'},
                        {field: 'mobile', title: __('手机'), operate: 'LIKE'},

                        {field: 'remark', title: __('备注'), operate: 'LIKE'},
                        {
                            field: 'status',
                            title: __('Status'),
                            formatter: Table.api.formatter.status,
                            searchList: {1: __('已转客户'), 0: __('未转客户'), '-1': __('无效线索')}
                        },
                        {field: 'create_user.nickname', title: __('创建人'), operate: false, search: false},
                        {field: 'create_user_id', title: __('创建人'), visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname"'},
                        {
                            field: 'next_time',
                            title: __('下次跟进'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
                            extend: 'autocomplete="off"'
                        },
                        {
                            field: 'create_time',
                            title: __('创建时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
                            extend: 'autocomplete="off"'
                        },
                        {
                            field: 'update_time',
                            title: __('更新时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
                            extend: 'autocomplete="off"'
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'receive',
                                    text: '领取',
                                    title: '领取',
                                    icon: 'fa fa-check',
                                    url: 'facrm/clues/index/receive',
                                    classname: 'btn btn-xs btn-success  btn-ajax',
                                    success: function (data, ret) {
                                        $("a.btn-refresh").trigger("click");
                                    },
                                },
                            ]
                        },

                    ]
                ],
                onLoadSuccess: function () {
                    // 载入成功时执行
                    loadSuccess("clues_common")
                },
                onColumnSwitch: function () {
                    // 切换列时执行columnSwitch方法
                    columnSwitch("clues_common","clues_common_table")
                },
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
                searchFormVisible:true, //打开搜索

            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            // 批量领取事件
            $("#toolbar").on('click', '.btn-receive', function () {
                var that = this;
                var ids = Table.api.selectedids(table);
                Layer.confirm(
                    __('确定领取 %s 项?', ids.length),
                    {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                    function (index) {
                        Table.api.multi("del1", ids, table, that);
                        Layer.close(index);
                    }
                );
            });
            // 批量转移
            $("#toolbar").on('click', '.btn-divert', function () {
                var that = this;
                var ids = Table.api.selectedids(table);
                if (ids.length > 10) {
                    return;
                }
                var title = $(that).data('title') || $(that).attr("title") || __('Edit');
                var url = $(that).data('url');
                var data = $(that).data() || {};
                delete data.title;
                //循环弹出多个编辑框
                Fast.api.open(url + "/ids/" + ids, title, data);


            });

        },
        import: function () {
            Controller.api.bindevent();
        },
        transform:function(){
            Form.api.bindevent($("form[role=form]"));

            Fast.api.ajax({
                type: 'GET',
                url: 'facrm/fields/get_fields_html',
                data: {source: 'customer', 'id': 0,'tpl':'fields_6_2'}
            }, function (data) {
                $("#extend").html(data.html);
                Form.api.bindevent($("#extend"));
                return false;
            });
            require.config({
                    paths: {
                        'tagsinput': '../addons/facrm/js/jquery.tagsinput',
                        'autocomplete': '../addons/facrm/js/jquery.autocomplete',
                    },
                    shim: {
                        'autocomplete': {
                            deps: ['jquery'],
                            exports: '$.fn.extend'
                        },
                        'tagsinput': {
                            deps: ['jquery', 'autocomplete', 'css!../addons/facrm/css/jquery.tagsinput.min.css'],
                            exports: '$.fn.extend'
                        }
                    }
                }
            );
            require(['tagsinput'], function () {
                //标签输入
                var elem = "#c-tags";
                var tags = $(elem);
                tags.tagsInput({
                    width: 'auto',
                    defaultText: '输入后空格确认',
                    minInputWidth: 110,
                    height: '36px',
                    placeholderColor: '#999',
                    onChange: function (row) {
                        if (typeof callback === 'function') {

                        } else {
                            $(elem + "_addTag").focus();
                            $(elem + "_tag").trigger("blur.autocomplete").focus();
                        }
                    },
                    autocomplete: {
                        url: 'facrm/tag/autocomplete?type=customer',
                        minChars: 1,
                        menuClass: 'autocomplete-tags'
                    }
                });
            });
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/clues/index/recyclebin',
                }
            });

            var table = $("#table");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
            });
            var columnss = [
                {checkbox: true},
                {field: 'id', title: 'ID'},
                {field: 'name', title: __('名称'), operate: "LIKE"},

                {field: 'telephone', title: __('电话'), operate: 'LIKE'},
                {field: 'mobile', title: __('手机'), operate: 'LIKE'},

                {field: 'create_user.nickname', title: __('创建人'), operate: false, search: false},
                {field: 'create_user_id', title: __('创建人'), visible: false},
                {field: 'owner_user.nickname', title: __('负责人'), operate: false, search: false,
                    addclass: 'selectpage',
                    extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname"'},
                {field: 'owner_user_id', title: __('负责人'), visible: false,
                    addclass: 'selectpage',
                    extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname"'},
                {
                    field: 'delete_time',
                    title: __('删除时间'),
                    formatter: Table.api.formatter.datetime,
                    operate: 'RANGE',
                    addclass: 'datetimerange',
                    sortable: true,
					extend: 'autocomplete="off"'
                },
                {
                    field: 'status',
                    title: __('Status'),
                    formatter: Table.api.formatter.status,
                    searchList: {1: __('已转客户'), 0: __('未转客户'), '-1': __('无效线索')}
                },
                {
                    field: 'operate',
                    width: '130px',
                    title: __('Operate'),
                    table: table,
                    events: Table.api.events.operate,
                    buttons: [
                        {
                            name: 'Restore',
                            text: __('Restore'),
                            classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                            icon: 'fa fa-rotate-left',
                            url: 'facrm/clues/index/restore',
                            refresh: true
                        },
                        {
                            name: 'Destroy',
                            text: __('Destroy'),
                            classname: 'btn btn-xs btn-danger btn-ajax  btn-destroyit',
                            icon: 'fa fa-times',
                            url: 'facrm/clues/index/destroy',
                            refresh: true
                        }
                    ],
                    formatter: Table.api.formatter.operate
                }
            ];


            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    columnss
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            // 绑定TAB事件
            $('.panel-heading ul[data-field] li a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field = $(this).closest("ul").data("field");
                var value = $(this).data("value");
                $(".commonsearch-table input[name=" + field + "]").val(value);
                return false;
            });
        },
        diyorder:function(){
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                if ("undefined" == typeof clues_id) {
                    clues_id = 0;
                }
                Fast.api.ajax({
                    type: 'GET',
                    url: 'facrm/fields/get_fields_html',
                    data: {source: 'clues', 'id': clues_id}
                }, function (data) {
                    $("#extend").html(data.html);
                    Form.api.bindevent($("#extend"));
                    return false;
                });
                require.config({
                        paths: {
                            'tagsinput': '../addons/facrm/js/jquery.tagsinput',
                            'autocomplete': '../addons/facrm/js/jquery.autocomplete',
                        },
                        shim: {
                            'autocomplete': {
                                deps: ['jquery'],
                                exports: '$.fn.extend'
                            },
                            'tagsinput': {
                                deps: ['jquery', 'autocomplete', 'css!../addons/facrm/css/jquery.tagsinput.min.css'],
                                exports: '$.fn.extend'
                            }
                        }
                    }
                );
                require(['tagsinput'], function () {
                    //标签输入
                    var elem = "#c-tags";
                    var tags = $(elem);
                    tags.tagsInput({
                        width: 'auto',
                        defaultText: '输入后空格确认',
                        minInputWidth: 110,
                        height: '36px',
                        placeholderColor: '#999',
                        onChange: function (row) {
                            if (typeof callback === 'function') {

                            } else {
                                $(elem + "_addTag").focus();
                                $(elem + "_tag").trigger("blur.autocomplete").focus();
                            }
                        },
                        autocomplete: {
                            url: 'facrm/tag/autocomplete?type=customer',
                            minChars: 1,
                            menuClass: 'autocomplete-tags'
                        }
                    });
                });

                //云呼
                $(".cloudcall").click(function () {
                    var that = this;
                    var type = $(that).data('type');
                    var typeid = $(that).data('typeid');
                    var name = $(that).data('name');
					var field = $(that).data('field');

					Fast.api.ajax({
						url: 'facrm/setting/cloudcall/call',
						data: {type: type, typeid: typeid,field:field,name:name}
                    }, function (data) {
                        Toastr.success("呼叫成功！");
                        return false;
                    });
                });
            },
            formatter: {
                thumb: function (value, row, index) {
                    if (!value) return '';
                    value = value === null ? '' : value.toString();
                    var arr = value.split(',');
                    var html = [];
                    $.each(arr, function (i, value) {

                        var reg = /\.(png|jpg|gif|jpeg|webp)$/;
                        if (reg.test(value)) {
                            html.push('<a href="' + Fast.api.cdnurl(value) + '" target="_blank"><img src="' + Fast.api.cdnurl(value) + '" alt="" style="max-height:90px;max-width:120px"></a>');
                        } else {
                            if (row.imagetype == undefined) row.imagetype = /[^\.]+$/.exec(value);
                            html.push('<a href="' + Fast.api.cdnurl(value) + '" target="_blank"><img src="' + Fast.api.fixurl("ajax/icon") + "?suffix=" + row.imagetype + '" alt="" style="max-height:90px;max-width:120px"></a>');
                        }
                    });
                    return html.join(' ');
                },
                url: function (value, row, index) {
                    return '<a href="' + row.fullurl + '" target="_blank" class="label bg-green">' + row.url + '</a>';
                },
                filename: function (value, row, index) {
                    return '<div style="width:180px;margin:0 auto;text-align:center;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;">' + Table.api.formatter.search.call(this, value, row, index) + '</div>';
                },
            }
        }
    };
    return Controller;
});